<?php

namespace app\model;

use mon\orm\Model;
use mon\util\Instance;

/**
 * 访客模型
 *
 * Class ChatVisitor
 * @copyright 2021-03-25 mon-console
 * @version 1.0.0
 */
class ChatVisitorModel extends Model
{
    use Instance;

    /**
     * 操作表
     *
     * @var string
     */
    protected $table = 'chat_visitor';

    /**
     * 新增自动写入字段
     *
     * @var array
     */
    protected $insert = ['create_time', 'update_time'];

    /**
     * 更新自动写入字段
     *
     * @var array
     */
    protected $update = ['update_time'];

    /**
     * 验证器
     *
     * @var string
     */
    protected $validate = \app\validate\Chat::class;

    /**
     * 查询信息
     *
     * @param array $where where条件
     * @param mixed $field 查询字段
     * @return mixed
     */
    public function getInfo(array $where, $field = '*')
    {
        $info = $this->where($where)->field($field)->find();
        if (!$info) {
            $this->error = '访客信息不存在';
            return false;
        }

        return $info;
    }

    /**
     * 记录访客ID到数据库中
     *
     * @param string $uid   访客ID
     * @param string $ip    访客IP
     * @return boolean
     */
    public function record($uid, $ip = '')
    {
        $info = $this->getInfo(['visitid' => $uid]);
        if (!$info) {
            $save = $this->save(['visitid' => $uid, 'ip' => $ip], null, true);
            if (!$save) {
                return false;
            }

            return $save;
        }

        return $info['id'];
    }

    /**
     * 修改客户信息
     *
     * @param array $data 客户信息
     * @param string $visitid 客户ID
     * @return boolean
     */
    public function modify(array $data, $visitid)
    {
        $check = $this->validate()->data($data)->scope('clent_info')->check();
        if ($check !== true) {
            $this->error = $this->validate()->getError();
            return false;
        }

        // 保存数据
        $save = $this->save([
            'username'  => isset($data['username']) ? $data['username'] : '',
            'email'     => isset($data['email']) ? $data['email'] : '',
            'moble'     => isset($data['moble']) ? $data['moble'] : '',
            'qq'        => isset($data['qq']) ? $data['qq'] : '',
            'address'   => isset($data['address']) ? $data['address'] : '',
            'remark'    => isset($data['remark']) ? $data['remark'] : '',
        ], ['visitid' => $visitid]);
        if (!$save) {
            $this->error = '保存信息失败';
            return false;
        }

        return true;
    }

    /**
     * 自动完成create_time字段
     * 
     * @param mixed $val 默认值
     * @param array  $row 列值
     * @return string
     */
    protected function setCreateTimeAttr($val)
    {
        return time();
    }

    /**
     * 自动完成update_time字段
     * 
     * @param mixed $val 默认值
     * @param array  $row 列值
     * @return string
     */
    protected function setUpdateTimeAttr($val)
    {
        return time();
    }
}
